//
//  CMMCIOTNetWork.swift
//  CMCCIOTSwift
//
//  Created by isoftstone on 2017/4/17.
//  Copyright © 2017年 isoftstone. All rights reserved.
//

import Alamofire
import UIKit
let SERVICE_URL     = "https://httpbin.org/post"
class CommonNetWorkKit: NSObject {
    //单例模式
    static var shared:CommonNetWorkKit {
        struct Static {
            static let instance: CommonNetWorkKit = CommonNetWorkKit()
        }
        return Static.instance
    }
    
    

    func post(params :  Dictionary<String, String>  ,requestComplete:@escaping (HTTPURLResponse?, Result<String>) -> Void) {
        
        let request = Alamofire.request(SERVICE_URL, method: .post, parameters: params, encoding:JSONEncoding.default, headers: [:])
        request.responseString { (response) in
            if(response.result.isSuccess){
                requestComplete(response.response,response.result)
            }else{
                requestComplete(response.response,response.result)
            }
        }
    }
    
    func postData(params :  Dictionary<String, String>  ,requestComplete:@escaping (HTTPURLResponse?, Result<Data>) -> Void)  {
        
        let request = Alamofire.request(SERVICE_URL, method: .post, parameters: params, encoding: "", headers: [:])
        request.responseData { (response) in
            requestComplete(response.response,response.result)
        }
        
        
    }
}

extension String: ParameterEncoding {
    
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }
    
}
